/**
 * Created by wenguangjia on 2017/4/25.
 */
(function () {
    'use strict';
    angular
        .module('logcenterApp')
        .controller('svcAnalysisController', svcAnalysisController);
    svcAnalysisController.$inject = ['$scope', 'searchService', 'SvcAnalysisService', 'toaster'];

    function svcAnalysisController($scope, searchService, SvcAnalysisService, toaster) {
        var notify = function (type, title, message) {
            toaster.pop(type, title, message);
        };

        $scope.beginDateTime = getToday00Clock();
        $scope.endDateTime = getToday11Clock();
        $scope.queryType = "0";
        $scope.svcName = "";


        $scope.query = function () {
            var beginDateTime = $scope.beginDateTime.Format("yyyy-MM-ddThh:mm:ss.S");
            var endDateTime = $scope.endDateTime.Format("yyyy-MM-ddThh:mm:ss.S");
            if ($scope.queryType === "0") {
                $scope.gridOptions.columns = serverExecuteInfoColumns;
                SvcAnalysisService.query($scope.partition, beginDateTime, endDateTime, $scope.svcName).then(
                    function (resp) {
                        $scope.queryTypeForCharts = "0";
                        $scope.gridOptions.dataSource = {
                            data: resp,
                            schema: {
                                model: $scope.serverExecuteInfoModel
                            }
                        };
                        $scope.detailBeginDateTime = beginDateTime;
                        $scope.detailEndDateTime = endDateTime;
                        initOption(resp);
                    }, function (error) {
                        console.log(error);
                        notify('error', '失败', error.message);
                    });
            }
            else {
                var seconds = getDiffSeconds($scope.beginDateTime, $scope.endDateTime);
                if (seconds > 24 * 60 * 60) {
                    notify("warning", "提示", "相差时间不能超过24小时");
                    return;
                }
                $scope.gridOptions.columns = svrExecPer10MinInfoColumns;
                SvcAnalysisService.querySvrExecPer10MinInfo($scope.partition, beginDateTime, endDateTime,$scope.svcName).then(
                    function (resp) {
                        $scope.queryTypeForCharts = "1";
                        $scope.gridOptions.dataSource = {
                            data: resp,
                            schema: {
                                model: $scope.svrExecPer10MinInfoModel
                            }
                        };
                        initSvrExecPer10MinOption(resp);
                    }, function (error) {
                        console.log(error);
                        notify('error', '失败', error.message);
                    });
            }
        };

        searchService.getPartition({cname: null, fname: null, ename: null}).then(function (resp) {
            $scope.partitionData = resp.data;
            $scope.partition = $scope.partitionData[0].ename;
        }, function (error) {
            notify('error', '失败', '查询分区失败，' + error);
        });

        $scope.partitionHeaderTmp = kendo.template($("#partition-header-template").html());
        $scope.partitionTmp = kendo.template($("#partition-template").html());


        var serverExecuteInfoColumns = [
            {field: "pid", title: "进程号"},
            {field: "server", title: "服务号"},
            {field: "count", title: "次数"},
            {field: "min", title: "最小时长"},
            {field: "max", title: "最大时长"},
            {
                field: "avg", title: "平均值", template: function (dataItem) {
                return kendo.parseInt(dataItem.avg);
            }
            },
            {
                field: "std_deviation", title: "标准差", template: function (dataItem) {
                return kendo.parseInt(dataItem.std_deviation);
            }
            },
            {field: "hostName", title: "主机名"}
        ];

        var svrExecPer10MinInfoColumns = [
            {
                field: "key", title: "时间",
                // template: function (dataItem) {
                // return getDate(dataItem.key);
                // }
            },
            {field: "count", title: "次数"}
        ];

        $scope.serverExecuteInfoModel = kendo.data.Model.define({
            fields: {
                pid: {type: 'number'},
                server: {type: 'string'},
                count: {type: 'number'},
                min: {type: 'number'},
                max: {type: 'number'},
                avg: {type: 'number'},
                std_deviation: {type: 'number'},
                hostName: {type: 'string'}
            }
        });

        $scope.svrExecPer10MinInfoModel = kendo.data.Model.define({
            fields: {
                key: {type: 'string'},
                count: {type: 'number'}
            }
        });

        $scope.gridOptions = {
            columns: serverExecuteInfoColumns,
            dataSource: $scope.dataSource
        };

        /*$scope.dataSource = new kendo.data.DataSource({
            autoBind: true,
            transport: {
                read: function (e) {
                    var beginDateTime = $scope.beginDateTime.Format("yyyy-MM-ddThh:mm:ss.SZ");
                    var endDateTime = $scope.endDateTime.Format("yyyy-MM-ddThh:mm:ss.SZ");
                    if ($scope.queryType === "0") {
                        SvcAnalysisService.query($scope.partition, beginDateTime, endDateTime).then(
                            function (resp) {
                                e.success(resp);
                                $scope.detailBeginDateTime = beginDateTime;
                                $scope.detailEndDateTime = endDateTime;
                                initOption(resp);
                            }, function (error) {
                                console.log(error);
                                e.error(error);
                                notify('error', '失败', error.message);
                            });
                    }
                    if ($scope.queryType === "1") {
                        SvcAnalysisService.querySvrExecPer10MinInfo($scope.partition, beginDateTime, endDateTime).then(
                            function (resp) {
                                e.success(resp);
                                initSvrExecPer10MinOption(resp);
                            }, function (error) {
                                console.log(error);
                                e.error(error);
                                notify('error', '失败', error.message);
                            });
                    }

                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if ($scope.partition == '') {
                    e.preventDefault();
                }
            }
        });*/


        /**
         * Detail
         */
        $scope.pid = "";

        $scope.svcExecuteInfoModel = kendo.data.Model.define({
            fields: {
                service: {type: 'string'},
                count: {type: 'number'},
                min: {type: 'number'},
                max: {type: 'number'},
                avg: {type: 'number'},
                std_deviation: {type: 'number'}
            }
        });

        $scope.detailOptions = function (dataItem) {
            if ($scope.queryType === "0") {
                return {
                    dataSource: {
                        transport: {
                            read: function (e) {
                                SvcAnalysisService.queryDetail($scope.partition, dataItem.pid, $scope.detailBeginDateTime,
                                    $scope.detailEndDateTime).then(
                                    function (resp) {
                                        e.success(resp);
                                    }, function (error) {
                                        e.error(error);
                                        console.log(error);
                                        notify('error', '失败', error.message);
                                    });
                            }
                        }
                    },
                    scrollable: false,
                    sortable: true,
                    resizable: true,
                    columns: $scope.svcExecuteInfoColumns
                };
            } else {
                return {
                    dataSource: {
                        transport: {
                            read: function (e) {
                                SvcAnalysisService.querySvrExecPer10MinInfoDetail(dataItem.key).then(
                                    function (resp) {
                                        e.success(resp);
                                    }, function (error) {
                                        e.error(error);
                                        console.log(error);
                                        notify('error', '失败', error.message);
                                    });
                            }
                        }
                    },
                    scrollable: false,
                    sortable: true,
                    resizable: true,
                    columns: $scope.srvExecPer10MinInfoDetailColumns
                };
            }

        };

        $scope.svcExecuteInfoColumns = [
            {field: "service", title: "服务"},
            {field: "count", title: "次数"},
            {field: "min", title: "最小时长"},
            {field: "max", title: "最大时长"},
            {
                field: "avg", title: "平均值", template: function (dataItem) {
                return kendo.parseInt(dataItem.avg);
            }
            },
            {
                field: "std_deviation", title: "标准差", template: function (dataItem) {
                return kendo.parseInt(dataItem.std_deviation);
            }
            }
        ];

        $scope.srvExecPer10MinInfoDetailColumns = [
            {field: "server", title: "服务号", width: 100},
            {field: "sum", title: "调用时长", width: 70},
            {field: "svc1", title: "svc1/时长", width: 150},
            {field: "svc2", title: "svc2/时长", width: 150},
            {field: "svc3", title: "svc3/时长", width: 150},
            {field: "svc4", title: "svc4/时长", width: 150},
            {field: "svc5", title: "svc5/时长", width: 150},
            {field: "hostName", title: "主机名", width: 80}

        ];


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

        function initOption(resp) {
            var xServer = [];
            var yMin = [];
            var yMax = [];
            var yAvg = [];
            var yStdDeviation = [];
            angular.forEach(resp, function (item, index) {
                var xValue = item.server+"/"+item.hostName;
                xServer.push(xValue);
                yMin.push(kendo.parseInt(item.min));
                yMax.push(kendo.parseInt(item.max));
                yAvg.push(kendo.parseInt(item.avg));
                yStdDeviation.push(kendo.parseInt(item.std_deviation));
            });
            $scope.option0 = {
                borderWidth: 5,
                borderColor: '#bbbbbb',
                grid: {
                    left: '3%',
                    right: '4%',
                    // bottom: '3%',
                    containLabel: true
                },
                tooltip: {},
                toolbox: {
                    show: true,
                    orient: 'horizontal',      // 布局方式，默认为水平布局，可选为：
                                               // 'horizontal' ¦ 'vertical'
                    x: 'right',                // 水平安放位置，默认为全图右对齐，可选为：
                                               // 'center' ¦ 'left' ¦ 'right'
                                               // ¦ {number}（x坐标，单位px）
                    y: 'top',                  // 垂直安放位置，默认为全图顶端，可选为：
                                               // 'top' ¦ 'bottom' ¦ 'center'
                                               // ¦ {number}（y坐标，单位px）
                    color: ['#1e90ff', '#22bb22', '#4b0082', '#d2691e'],
                    backgroundColor: 'rgba(0,0,0,0)', // 工具箱背景颜色
                    borderColor: '#ccc',       // 工具箱边框颜色
                    borderWidth: 0,            // 工具箱边框线宽，单位px，默认为0（无边框）
                    padding: 5,                // 工具箱内边距，单位px，默认各方向内边距为5，
                    showTitle: true,
                    feature: {
                        magicType: {
                            show: true,
                            title: {
                                stack: '堆积',
                                tiled: '平铺'
                            },
                            type: ['stack', 'tiled']
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        xAxisIndex: [0],
                        top: "90%",
                        handleSize: 20,
                        dataBackgroundColor: '#eee',
                        // 数据背景颜色
                        fillerColor: 'rgba(144,197,237,0.2)',
                        // 填充颜色
                        handleColor: '#1790cf'    // 手柄颜色

                    }

                ],
                xAxis: [
                    {

                        type: 'category',
                        axisLabel: {
                            interval: 0,    // {number}
                            rotate: 45
                        },
                        axisTick: false,
                        axisLine: {
                            show: false
                        },
                        splitArea: {
                            show: false
                            /* areaStyle:{
                             color:['RGB(249,249,249)','RGB(249,249,249)']
                             }*/
                        },
                        splitLine: {
                            show: true
                        },
                        data: xServer
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        min: 0,
                        /* max: '100%',
                         interval: '10%',*/
                        // splitArea: {
                        //     show: true,
                        //     areaStyle: {
                        //         color: ['RGB(255,255,255)', 'RGB(209,249,249)']
                        //     }
                        // },
                        axisTick: false,
                        axisLine: {
                            show: false
                        },
                        splitLine: {
                            show: true
                        },
                        axisLabel: {
                            formatter: '{value} ms'
                        }
                    }
                ],
                legend: {
                    /*show:true,
                     x:"center",
                     y:"top",
                     orient:'vertical',*/
                    data: ['最小时长', '最大时长', '平均值', '标准差']
                },
                series: [
                    {
                        name: '最小时长',
                        type: 'bar',
                        stack: 'xxx',
                        barCategoryGap: '40%',
                        barGap: '0%',
                        itemStyle: {
                            normal: {
                                color: "#e98f6f"

                            }
                        },
                        data: yMin
                    },
                    {
                        name: '最大时长',
                        type: 'bar',
                        stack: 'xxx',
                        barCategoryGap: '40%',
                        barGap: '0%',
                        itemStyle: {
                            normal: {
                                color: "#c23531",
                                label:
                                    {show: false}
                            }
                        },
                        data: yMax
                    },
                    {
                        name: '平均值',
                        type: 'bar',
                        stack: 'xxx',
                        barCategoryGap: '40%',
                        barGap: '0%',
                        itemStyle: {
                            normal: {
                                color: "#334b5c",
                                label:
                                    {show: false}
                            }
                        },
                        data: yAvg
                    },
                    {
                        name: '标准差',
                        type: 'bar',
                        stack: 'xxx',
                        barCategoryGap: '40%',
                        barGap: '0%',
                        itemStyle: {
                            normal: {
                                color: "#6ab0b8",
                                label:
                                    {show: false}
                            }
                        },
                        data: yStdDeviation
                    }
                ]
            };
        }

        function initSvrExecPer10MinOption(resp) {
            var xTime = [];
            var yTop1 = [];
            var yTop2 = [];
            var yTop3 = [];
            var yTop4 = [];
            var yTop5 = [];
            var yTop6 = [];
            var yTop7 = [];
            var yTop8 = [];
            var yTop9 = [];
            var yTop10 = [];
            angular.forEach(resp, function (item, index) {
                xTime.push(item.key);
                if (item.serverList[0] !== undefined) {
                    yTop1.push(item.serverList[0].sum);
                } else {
                    yTop1.push("");
                }
                if (item.serverList[1] !== undefined) {
                    yTop2.push(item.serverList[1].sum);
                } else {
                    yTop2.push("");
                }
                if (item.serverList[2] !== undefined) {
                    yTop3.push(item.serverList[2].sum);
                } else {
                    yTop3.push("");
                }
                if (item.serverList[3] !== undefined) {
                    yTop4.push(item.serverList[3].sum);
                } else {
                    yTop4.push("");
                }
                if (item.serverList[4] !== undefined) {
                    yTop5.push(item.serverList[4].sum);
                } else {
                    yTop5.push("");
                }
                if (item.serverList[5] !== undefined) {
                    yTop6.push(item.serverList[5].sum);
                } else {
                    yTop6.push("");
                }
                if (item.serverList[6] !== undefined) {
                    yTop7.push(item.serverList[6].sum);
                } else {
                    yTop7.push("");
                }
                if (item.serverList[7] !== undefined) {
                    yTop8.push(item.serverList[7].sum);
                } else {
                    yTop8.push("");
                }
                if (item.serverList[8] !== undefined) {
                    yTop9.push(item.serverList[8].sum);
                } else {
                    yTop9.push("");
                }
                if (item.serverList[9] !== undefined) {
                    yTop10.push(item.serverList[9].sum);
                } else {
                    yTop10.push("");
                }
            });
            $scope.option1 = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    show: true,
                    orient: 'horizontal',      // 布局方式，默认为水平布局，可选为：
                                               // 'horizontal' ¦ 'vertical'
                    x: 'right',                // 水平安放位置，默认为全图右对齐，可选为：
                                               // 'center' ¦ 'left' ¦ 'right'
                                               // ¦ {number}（x坐标，单位px）
                    y: 'top',                  // 垂直安放位置，默认为全图顶端，可选为：
                                               // 'top' ¦ 'bottom' ¦ 'center'
                                               // ¦ {number}（y坐标，单位px）
                    color: ['#1e90ff', '#22bb22', '#4b0082', '#d2691e'],
                    backgroundColor: 'rgba(0,0,0,0)', // 工具箱背景颜色
                    borderColor: '#ccc',       // 工具箱边框颜色
                    borderWidth: 0,            // 工具箱边框线宽，单位px，默认为0（无边框）
                    padding: 5,                // 工具箱内边距，单位px，默认各方向内边距为5，
                    showTitle: true,
                    feature: {
                        magicType: {
                            show: true,
                            title: {
                                stack: '堆积',
                                tiled: '平铺'
                            },
                            type: ['stack', 'tiled']
                        }
                    }
                },
                calculable: true,
                dataZoom: [
                    {
                        type: 'slider',
                        show: true,
                        xAxisIndex: [0],
                        top: "90%",
                        handleSize: 20,
                        dataBackgroundColor: '#eee',
                        // 数据背景颜色
                        fillerColor: 'rgba(144,197,237,0.2)',
                        // 填充颜色
                        handleColor: '#1790cf'    // 手柄颜色

                    }

                ],
                legend: {
                    data: ['Top1', 'Top2', 'Top3', 'Top4', 'Top5', 'Top6', 'Top7', 'Top8', 'Top9', 'Top10']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    // bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        data: xTime
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            formatter: '{value} ms'
                        }
                    }
                ],
                series: [
                    {
                        name: 'Top1',
                        type: 'bar',
                        data: yTop1
                    },
                    {
                        name: 'Top2',
                        type: 'bar',
                        data: yTop2
                    },
                    {
                        name: 'Top3',
                        type: 'bar',
                        data: yTop3
                    },
                    {
                        name: 'Top4',
                        type: 'bar',
                        data: yTop4
                    },
                    {
                        name: 'Top5',
                        type: 'bar',
                        data: yTop5
                    },
                    {
                        name: 'Top6',
                        type: 'bar',
                        data: yTop6
                    },
                    {
                        name: 'Top7',
                        type: 'bar',
                        data: yTop7
                    },
                    {
                        name: 'Top8',
                        type: 'bar',
                        data: yTop8
                    },
                    {
                        name: 'Top9',
                        type: 'bar',
                        data: yTop9
                    },
                    {
                        name: 'Top10',
                        type: 'bar',
                        data: yTop10
                    }
                ]
            };
        }


    }
})();
